// pages/edit-address/edit-address.js
var common = require("../../utils/public.js") //引入public.js脚本
import WxValidate from "../../utils/wxValidate.js";
var api = require("../../utils/api");
var cf = require("../../config.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    array: [], //城市列表
    // switch1Checked: 0,//默认
    mapAddr: [], //map返回地址列表
    resAddr: {},
    obj: {},
    form: {
      linkMan: "", //收货人
      linkTel: "", //联系电话
      buildNo: "", //详细地址
      newAdd: null,
      resAddr: {}
    },
    // 城市下拉
    multiArray: [
      [],
      []
    ],
    multiIndex: [],
  },
  handlePickerChange(e) {
    console.log(e)
    let mapAddr = this.data.mapAddr;
    this.setData({
      // mapAddr: mapAddr[e.detail.value[1]],
      resAddr: mapAddr[e.detail.value[1]],
      multiIndex: e.detail.value
    })
  },
  // 城市下拉
  handleChooseAddr(e) {
    var data = {
      multiArray: this.data.multiArray,
      multiIndex: this.data.multiIndex
    };
    data.multiIndex[e.detail.column] = e.detail.value;
    let vals = data.multiArray[e.detail.column][e.detail.value]
    if (e.detail.column == 0) {
      api.personChooseAddr(vals)
        .then(res => {
          let id = res.result[0][0].id;
          api.personChooseAddrTwo(id)
            .then(res2 => {
              let newArr = []
              let mapAddr = []
              res2.result[0].forEach((v, i) => {
                newArr.push(v.fullname)
              })
              this.setData({
                mapAddr: res2.result[0],
                newArr,
                // ['multiArray[1]']: newArr
              })
              data.multiArray[1] = newArr
              data.multiIndex[1] = 0;
              this.setData(data);
            })
        })
    }

  },
  //保存
  handleSubmit: common.throttleFunc(function (e) {
    let that = this;
    //收货人，电话，地址，详细地址
    let {
      linkMan,
      linkTel,
      buildNo
    } = that.data.form;
    // 经纬度 区域 区域编码
    let { lat, lng } = that.data.resAddr.location
    let { fullname, id } = that.data.resAddr;
    let { multiArray, multiIndex } = that.data
    let addrs = multiArray[0][multiIndex[0]] + multiArray[1][multiIndex[1]]

    if (multiIndex == 0) {
      wx.showModal({
        content: "请选择城市！",
        showCancel: false
      })
      return false;
    }
    if (!this.WxValidate.checkForm(e)) {
      let err = this.WxValidate.errorList[0]
      this.showModal(err);
      return false;
    }
    // 调用接口
    api.formSubmit({
      addr: addrs,
      linkman: e.detail.value.linkMan, //收货人
      linkTel: e.detail.value.linkTel, //收货人电话
      latitude: lat, //纬度
      longitude: lng, //经度
      cityAddr: fullname, // 所属区
      cityCode: id, // 区码
      buildNo: e.detail.value.buildNo, //详细地址【看后台参数***】
      // isFlag: switch1Checked,//默认地址状态【看后台参数***】
      userInfoId: wx.getStorageSync("openId"), //用户id
      cityId: wx.getStorageSync("cityId"), //城市编号
      addressType: 2 //个人
    })
      .then(res => {
        if (res.result) {
          if (this.data.newAdd == null) {
            wx.request({
              url: `${cf.url}/admin/user/loginUserType`,
              data: {
                openid: wx.getStorageSync("openId"),
                authUserId: '-1',
                type: 2,
                shopId: '-1'
              },
              header: {
                'content-type': 'application/json',
              },
              method: 'POST',
            })
          }
          wx.showToast({
            title: '提交成功',
            duration: 1500,
            success: () => {
              if (that.data.type) {
                let pages = getCurrentPages();//当前页面栈
                if (pages.length > 1) {
                  let beforePage = pages[pages.length - 2];//获取上一个页面实例对象
                  beforePage.addrs();//触发父页面中的方法
                  wx.navigateBack()
                }
              } else {
                wx.switchTab({
                  url: '/pages/my/my',
                })
              }
            }
          })
        }
      })
  }),
  onLoad: function (options) {
    this.setData({
      newAdd: options.newAdd,
      type: options.type,
      // switch1Checked: Number(options.flag),//默认
      // form :{
      //   linkMan: options.takePerson,//收货人
      //   linkTel: options.linktel,//联系电话
      //   addr: options.addrs,//收货地址
      //   buildNo: options.buildNo,//详细地址
      // }
    })
    // 提示信息/城市接口
    this.initValidate();
  },
  onShow: function () {

  },


  //默认设置
  switch1Change: function (e) {
    this.setData({
      switch1Checked: e.detail.value ? 1 : 0
    })
  },
  // 错误信息
  showModal(err) {
    wx.showModal({
      content: err.msg,
      showCancel: false
    })
  },
  // 提示信息/城市接口
  initValidate() {
    let that = this;
    //城市接口(市)
    api.cityList({
      page: {
        size: 6,
        current: 0,
        isStartPage: false,
        pages: 1,
      }
    }).then(res => {
      if (res.result) {
        let array = that.data.array;
        let selector = res.object.records;
        selector.forEach((v) => {
          array.push(v.name)
        })
        // 城市1
        api.personChooseAddr(array[0])
          .then(res => {
            let id = res.result[0][0].id;
            // 城市2
            api.personChooseAddrTwo(id)
              .then(res2 => {
                let newArr = []
                // let mapAddr =[]
                res2.result[0].forEach((v, i) => {
                  newArr.push(v.fullname)
                })
                that.setData({
                  mapAddr: res2.result[0],
                  resAddr: res2.result[0][0],
                  ['multiArray[1]']: newArr,
                  array,
                  ['multiArray[0]']: array
                })
              })
          })
      }
    })
    // 信息
    let rules = {
      linkMan: {
        required: true,
        minlength: 2
      },
      linkTel: {
        required: true,
        tel: true,
      },
      buildNo: {
        required: true,
        minlength: 3
      }
    }
    let message = {
      linkMan: {
        required: "请填写收货人",
        minlength: "请填写正确收货人"
      },
      linkTel: {
        required: "请输入手机号",
        tel: "请输入正确手机号",
      },
      buildNo: {
        required: "请填写详细地址",
        minlength: "请重新填写详细地址"
      }
    }
    this.WxValidate = new WxValidate(rules, message)
  }
})